package cn.lmxdev.ptms.service.impl;

import cn.lmxdev.ptms.bean.exception.BizException;
import cn.lmxdev.ptms.bean.table.TTeacherStudent;
import cn.lmxdev.ptms.dao.ITeacherStudentDao;
import cn.lmxdev.ptms.service.ITeacherStudentServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeacherStudentServletImpl implements ITeacherStudentServlet {
    private final ITeacherStudentDao teacherStudentDao;

    @Autowired
    public TeacherStudentServletImpl(
            ITeacherStudentDao teacherStudentDao
    ) {
        this.teacherStudentDao = teacherStudentDao;
    }

    @Override
    @Transactional
    public TTeacherStudent get(Long id) {
        return this.teacherStudentDao.find(id);
    }

    @Override
    @Transactional
    public long add(TTeacherStudent teacherStudent) {
        // 插入数据
        if (!this.teacherStudentDao.insert(teacherStudent))
            throw new BizException("操作失败");

        // 返回ID
        return teacherStudent.getId();
    }

    @Override
    @Transactional
    public void remove(Long id) {
        // 删除数据
        if (!this.teacherStudentDao.delete(id))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public void edit(TTeacherStudent teacherStudent) {
        // 查旧数据
        TTeacherStudent oldTeacherStudent = this.teacherStudentDao.find(teacherStudent.getId());

        // 更新属性
        oldTeacherStudent.setStudentId(teacherStudent.getStudentId())
                .setFulfill(teacherStudent.getFulfill());

        // 保存数据
        if (!this.teacherStudentDao.update(oldTeacherStudent))
            throw new BizException("操作失败");
    }

    @Override
    @Transactional
    public long count(TTeacherStudent teacherStudent) {
        return this.teacherStudentDao.count(teacherStudent);
    }

    @Override
    @Transactional
    public List<TTeacherStudent> list(Long limit, Long page, TTeacherStudent teacherStudent) {
        return this.teacherStudentDao.select(page != null ? (page - 1) * limit : null, limit, teacherStudent);
    }
}
